<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  
  <meta name="renderer" content="webkit">
  <meta http-equiv="X-UA-Compatible" content="IE=edge" >
  <link rel="dns-prefetch" href="//litten.me">
  <title>pjax: 当ajax遇上pushState | Litten的博客</title>
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
  <meta name="description" content="var pjax = pushState + ajax;小时候，小浣熊方便面里面有各种水浒人物的卡片。我买了一包，吃了方便面，饱了。而我又买了第二包，不是想吃方便面，而是仅仅想得到里面的卡片…">
<meta property="og:type" content="article">
<meta property="og:title" content="pjax: 当ajax遇上pushState">
<meta property="og:url" content="//litten.me/2014/02/12/about-pjax/index.html">
<meta property="og:site_name" content="Litten的博客">
<meta property="og:description" content="var pjax = pushState + ajax;小时候，小浣熊方便面里面有各种水浒人物的卡片。我买了一包，吃了方便面，饱了。而我又买了第二包，不是想吃方便面，而是仅仅想得到里面的卡片…">
<meta property="og:updated_time" content="2016-09-30T14:42:26.000Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="pjax: 当ajax遇上pushState">
<meta name="twitter:description" content="var pjax = pushState + ajax;小时候，小浣熊方便面里面有各种水浒人物的卡片。我买了一包，吃了方便面，饱了。而我又买了第二包，不是想吃方便面，而是仅仅想得到里面的卡片…">
  
    <link rel="alternative" href="/atom.xml" title="Litten的博客" type="application/atom+xml">
  
  
    <link rel="icon" href="/assets/img/favicon.ico">
  
  <link rel="stylesheet" href="/main.css?v=4.0.0.css">
  

</head>

<body>
  <div id="container" q-class="show:isCtnShow">
    <canvas id="anm-canvas" class="anm-canvas"></canvas>
    <div class="left-col" q-class="show:isShow">
      <div class="overlay"></div>
<div class="intrude-less">
	<header id="header" class="inner">
		<a href="/" class="profilepic">
			<img src="/assets/blogImg/litten.png" class="js-avatar">
		</a>

		<hgroup>
		  <h1 class="header-author"><a href="/">Litten</a></h1>
		</hgroup>

		
		<p class="header-subtitle">胆小认生，不易相处</p>
		

		<nav class="header-menu">
			<ul>
			
				<li><a href="/">主页</a></li>
	        
				<li><a href="/photos">相册</a></li>
	        
			</ul>
		</nav>
		<nav class="header-smart-menu">
	        
    		
    			
    			<a data-idx="0" q-on="click: openSlider(e, 'innerArchive')" href="javascript:void(0)">所有文章</a>
    			
    			
            
    			
            
    			
    			<a data-idx="1" q-on="click: openSlider(e, 'aboutme')" href="javascript:void(0)">关于我</a>
    			
    			
            
		</nav>
		<nav class="header-nav">
			<div class="social">
				
					<a class="github" target="_blank" href="https://github.com/litten" title="github"><i class="icon-github"></i></a>
		        
					<a class="weibo" target="_blank" href="http://weibo.com/litten225" title="weibo"><i class="icon-weibo"></i></a>
		        
					<a class="rss" target="_blank" href="/atom.xml" title="rss"><i class="icon-rss"></i></a>
		        
			</div>
		</nav>
	</header>		
</div>

    </div>
    <div class="mid-col" q-class="show:isShow,hide:isShow|isFalse">
      <nav id="mobile-nav">
  	<div class="overlay">
  		<div class="slider-trigger"><i class="icon-sort"></i></div>
  		<h1 class="header-author js-mobile-header hide">Litten</h1>
  	</div>
	<div class="intrude-less">
		<header id="header" class="inner">
			<div class="profilepic">
				<img src="/assets/blogImg/litten.png" class="js-avatar">
			</div>
			<hgroup>
			  <h1 class="header-author">Litten</h1>
			</hgroup>
			
			<p class="header-subtitle">胆小认生，不易相处</p>
			
			<nav class="header-menu">
				<ul>
				
					<li><a href="/">主页</a></li>
		        
					<li><a href="/photos">相册</a></li>
		        
		        
		        	<li><a href="/archives">所有文章</a></li>
		        
				</ul>
			</nav>
			<nav class="header-nav">
				<div class="social">
					
						<a class="github" target="_blank" href="https://github.com/litten" title="github"><i class="icon-github"></i></a>
			        
						<a class="weibo" target="_blank" href="http://weibo.com/litten225" title="weibo"><i class="icon-weibo"></i></a>
			        
						<a class="rss" target="_blank" href="/atom.xml" title="rss"><i class="icon-rss"></i></a>
			        
				</div>
			</nav>
		</header>				
	</div>
</nav>

      <div id="wrapper" class="body-wrap">
        <div class="menu-l">
          <div class="canvas-wrap">
            <canvas data-colors="#eaeaea" data-sectionHeight="100" data-contentId="js-content" id="myCanvas1" class="anm-canvas"></canvas>
          </div>
          <div id="js-content" class="content-ll">
            <article id="post-about-pjax" class="article article-type-post " itemscope itemprop="blogPost">
  <div class="article-inner">
    
      <header class="article-header">
        
  
    <h1 class="article-title" itemprop="name">
      pjax: 当ajax遇上pushState
    </h1>
  

        <a href="/2014/02/12/about-pjax/" class="archive-article-date">
  	<time datetime="2014-02-12T00:55:00.000Z" itemprop="datePublished"><i class="icon-calendar icon"></i>2014-02-12</time>
</a>
      </header>
    
    <div class="article-entry" itemprop="articleBody">
      
        <blockquote>
<p>var pjax = pushState + ajax;<br>小时候，小浣熊方便面里面有各种水浒人物的卡片。我买了一包，吃了方便面，饱了。而我又买了第二包，不是想吃方便面，而是仅仅想得到里面的卡片…          </p>
</blockquote>
<a id="more"></a>
<p>##<strong>一、简介</strong><br>pushState是html5中提供的方法，用以</p>
<ul>
<li>无刷新的更新浏览器地址栏；            </li>
<li>如其名称，将新地址push到历史堆栈中            </li>
</ul>
<p>用法：<code>pushState(data, title ,url)</code>            </p>
<p>data为保存的对象，可以在window.onpopstate时获取到；title为页面标题；url为需地址栏和历史发生改变的url。<br>正是这点看似很平常的功能，跟ajax结合到一起产生了火花。因为，ajax最擅长的事情就是局部刷新页面。</p>
<p>##<strong>二、ajax的纠结历史</strong><br>一切可以从ajax最擅长的事情说起。<br>ajax作为一个异步请求模型，从最初设计开始，也许压根就没打算将它跟浏览器历史挂钩。原因是历史堆栈所记录的，某种意思上可以说是顺序，跟我们理解的“同步”更为密切。</p>
<p>因而，<code>ajax可以无刷新改变页面内容，却无法改变页面的url</code>。</p>
<ul>
<li>####历史问题1 - 如何操控历史</li>
</ul>
<p>当单页面越来越流行，操作记录却很容易被忽略。假设有这样的单页面，按照分类点击，界面逐层递进：<code>体育 - 篮球 -nba -马刺队 - 邓肯</code><br>当我们点了4下到“邓肯”界面时，一个不小心的刷新，出现在你面前的也许是“体育”。原因是操作记录没有被记录。<br>而通常的解决方案是修改hash，每递进一层，去更新url的hash值，这样的方法：</p>
<ol>
<li>刷新时预先判断url的hash，从而知道这是哪一层，加载相应数据；          </li>
<li>支持了历史</li>
</ol>
<p>这样的方式貌似比较完善，其实不然。</p>
<ul>
<li>####历史问题2 - 对搜索引擎不友好</li>
</ul>
<p>最大的问题是，hash后生成的内容是不会被搜索引擎引用到。数据不能被爬取，无疑是浪费和损失。因此google放言，咱可以约定个协议：<code>#!xxx</code>这样hash的url，google也去爬取。称之为<code>hash bang</code>（哈希大爆炸？）。这一协议，在g+，twitter，人人，新浪微博上都可以看到。</p>
<p>事实上，ajax最或缺的两个问题，恰好被pushState的功能补充完善。</p>
<p>##<strong>三、pjax带来的价值</strong><br>除去补齐了ajax的问题，我们发现pjax会给web带来更多的好处。<br>回到开始说的“两包方便面”，我的意思是，有时你访问两个url，部分数据是相同的。比如百度贴吧，第一页和第二页的区别只是帖子内容（卡片）的不同，网站外框部分（方便面）都是一样的，这些东西就不需要在页面刷新时重复加载。</p>
<p>ajax处理这样的局部刷新，已经给我们带来了web2.0的体验，而加上pushstate的ajax则更进一步：</p>
<ol>
<li>一个url对应一套数据，有利于SEO；</li>
<li>更改数据和url时，只是局部刷新，带来较好的用户体验；</li>
<li>兼容性好，对不支持pushstate的浏览器，url也能正常请求页面（虽然有重复加载）；</li>
<li>刷新页面时，由于是url唯一，能正常加载到用户希望看到的数据，比处理hash的方式更方便；</li>
<li>后退与前进的浏览器操作，依然可以局部刷新（通过onpushstate事件捕获）</li>
</ol>
<p>##<strong>四、注意事项</strong></p>
<p>然而pjax不等于单纯的分离使用pushstate与ajax，还必须得做一些封装。缘于以下我能想到的注意事项：</p>
<ul>
<li>服务器端增加额外处理逻辑<br>服务器端，需要根据请求的参数，作出全页渲染或局部渲染响应<figure class="highlight groovy"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div></pre></td><td class="code"><pre><div class="line"><span class="string">Accept:</span>text<span class="regexp">/html, */</span>*; q=<span class="number">0.01</span></div><div class="line">Accept-<span class="string">Encoding:</span>gzip,deflate,sdch</div><div class="line"><span class="string">Connection:</span>keep-alive</div><div class="line"><span class="string">Host:</span>qianduannotes.duapp.com</div><div class="line">User-<span class="string">Agent:</span>AppleWebKit<span class="regexp">/537.36 (KHTML, like Gecko) Chrome/</span><span class="number">31.0</span><span class="number">.1650</span><span class="number">.63</span> Safari/<span class="number">537.36</span></div><div class="line">X-Requested-<span class="string">With:</span>XMLHttpRequest</div><div class="line">X-<span class="string">PJAX:</span><span class="literal">true</span></div></pre></td></tr></table></figure>
</li>
</ul>
<p>比如请求头部可以设定一个X-PAJX:true，用以通知服务器。</p>
<ul>
<li><p>浏览器兼容<br>假如浏览器不支持pushstate，提供fallback操作，直接打开需更改url的地址：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div></pre></td><td class="code"><pre><div class="line">$.support.pjax = <span class="built_in">window</span>.history &amp;&amp; <span class="built_in">window</span>.history.pushState</div><div class="line"><span class="comment">// Fallback</span></div><div class="line"><span class="keyword">if</span> ( !$.support.pjax ) &#123;</div><div class="line">  $.pjax = <span class="function"><span class="keyword">function</span>(<span class="params"> options </span>) </span>&#123;</div><div class="line">    <span class="built_in">window</span>.location = $.isFunction(options.url) ? options.url() : options.url</div><div class="line">  &#125;</div><div class="line">  $.fn.pjax = <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123; <span class="keyword">return</span> <span class="keyword">this</span> &#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
</li>
<li><p>本地存储机制<br>无疑pjax与localstorage共同使用可以进一步提升体验，但这一步容易忽略的是数据上报。</p>
</li>
</ul>
<p>##<strong>五、参考资料</strong><br><a href="https://github.com/defunkt/jquery-pjax" target="_blank" rel="external">jquery-pjax</a><br><a href="https://github.com/welefen/pjax" target="_blank" rel="external">welefen封装的pjax</a></p>

      

      
    </div>
    <div class="article-info article-info-index">
      
      
	<div class="article-tag tagcloud">
		<i class="icon-price-tags"></i>
		<ul class="article-tag-list"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/html5/">html5</a></li><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/js/">js</a></li></ul>
	</div>

      

      

      
        
<div class="share-btn share-icons tooltip-left">
  <div class="tooltip tooltip-east">
    <span class="tooltip-item">
      <a href="javascript:;" class="share-sns share-outer">
        <i class="icon icon-share"></i>
      </a>
    </span>
    <span class="tooltip-content">
      <div class="share-wrap">
        <div class="share-icons">
          <a class="weibo share-sns" href="javascript:;" data-type="weibo">
            <i class="icon icon-weibo"></i>
          </a>
          <a class="weixin share-sns wxFab" href="javascript:;" data-type="weixin">
            <i class="icon icon-weixin"></i>
          </a>
          <a class="qq share-sns" href="javascript:;" data-type="qq">
            <i class="icon icon-qq"></i>
          </a>
          <a class="douban share-sns" href="javascript:;" data-type="douban">
            <i class="icon icon-douban"></i>
          </a>
          <a class="qzone share-sns" href="javascript:;" data-type="qzone">
            <i class="icon icon-qzone"></i>
          </a>
          <a class="facebook share-sns" href="javascript:;" data-type="facebook">
            <i class="icon icon-facebook"></i>
          </a>
          <a class="twitter share-sns" href="javascript:;" data-type="twitter">
            <i class="icon icon-twitter"></i>
          </a>
          <a class="google share-sns" href="javascript:;" data-type="google">
            <i class="icon icon-google"></i>
          </a>
        </div>
      </div>
    </span>
  </div>
</div>

<div class="page-modal wx-share js-wx-box">
    <a class="close js-modal-close" href="javascript:;"><i class="icon icon-close"></i></a>
    <p>扫一扫，分享到微信</p>
    <div class="wx-qrcode">
      <img src="" alt="微信分享二维码">
    </div>
</div>

<div class="mask js-mask"></div>
      
      <div class="clearfix"></div>
    </div>
  </div>
</article>

  
<nav id="article-nav">
  
    <a href="/2014/02/22/thinner-than-1px-border/" id="article-nav-newer" class="article-nav-link-wrap">
      <i class="icon-circle-left"></i>
      <div class="article-nav-title">
        
          像素级细节：移动端1px border的实现
        
      </div>
    </a>
  
  
    <a href="/2014/02/05/my2013/" id="article-nav-older" class="article-nav-link-wrap">
      <div class="article-nav-title">我的2013下半年</div>
      <i class="icon-circle-right"></i>
    </a>
  
</nav>






<div class="duoshuo">
	<!-- 多说评论框 start -->
	<div class="ds-thread" data-thread-key="about-pjax" data-title="pjax: 当ajax遇上pushState" data-url="//litten.me/2014/02/12/about-pjax/"></div>
	<!-- 多说评论框 end -->
	<!-- 多说公共JS代码 start (一个网页只需插入一次) -->
	<script type="text/javascript">
	var duoshuoQuery = {short_name:"litten-hexo"};
	(function() {
		var ds = document.createElement('script');
		ds.type = 'text/javascript';ds.async = true;
		ds.src = (document.location.protocol == 'https:' ? 'https:' : 'http:') + '//static.duoshuo.com/embed.js';
		ds.charset = 'UTF-8';
		(document.getElementsByTagName('head')[0] 
		 || document.getElementsByTagName('body')[0]).appendChild(ds);
	})();
	</script>
	<!-- 多说公共JS代码 end -->
</div>





          </div>
        </div>
      </div>
      <footer id="footer">
  <div class="outer">
    <div id="footer-info">
    	<div class="footer-left">
    		&copy; 2016 Litten
    	</div>
      	<div class="footer-right">
      		<a href="http://hexo.io/" target="_blank">Hexo</a>  Theme <a href="https://github.com/litten/hexo-theme-yilia" target="_blank">Yilia</a> by Litten
      	</div>
    </div>
  </div>
</footer>
    </div>
    <script>
	var yiliaConfig = {
		mathjax: false,
		isHome: false,
		isPost: true,
		isArchive: false,
		isTag: false,
		isCategory: false,
		open_in_new: true,
		root: "/",
		innerArchive: true
	}
</script>

<script src="/./main.js?v=4.0.0.js"></script>


    
<div class="tools-col" q-class="show:isShow,hide:isShow|isFalse" q-on="click:stop(e)">
  <div class="tools-wrap">
    
    	<section class="tools-section tools-section-all" q-show="innerArchive">
        <div class="search-wrap">
          <input class="search-ipt" q-model="search" type="text" placeholder="find something…">
          <i class="icon-search icon" q-show="search|isEmptyStr"></i>
          <i class="icon-close icon" q-show="search|isNotEmptyStr" q-on="click:clearChose(e)"></i>
        </div>
        <div class="widget tagcloud search-tag">
          <p class="search-tag-wording">tag:</p>
          <label class="search-switch">
            <input type="checkbox" q-on="click:toggleTag(e)" q-attr="checked:showTags">
          </label>
          <ul class="article-tag-list" q-show="showTags">
             
              <li class="article-tag-list-item">
                <a href="javascript:void(0)">js</a>
              </li>
             
              <li class="article-tag-list-item">
                <a href="javascript:void(0)">html5</a>
              </li>
             
              <li class="article-tag-list-item">
                <a href="javascript:void(0)">设计</a>
              </li>
             
              <li class="article-tag-list-item">
                <a href="javascript:void(0)">杂谈</a>
              </li>
             
              <li class="article-tag-list-item">
                <a href="javascript:void(0)">游戏</a>
              </li>
             
              <li class="article-tag-list-item">
                <a href="javascript:void(0)">旧事</a>
              </li>
             
              <li class="article-tag-list-item">
                <a href="javascript:void(0)">coffeescript</a>
              </li>
             
              <li class="article-tag-list-item">
                <a href="javascript:void(0)">web</a>
              </li>
             
              <li class="article-tag-list-item">
                <a href="javascript:void(0)">旅行</a>
              </li>
             
              <li class="article-tag-list-item">
                <a href="javascript:void(0)">css</a>
              </li>
             
              <li class="article-tag-list-item">
                <a href="javascript:void(0)">css3</a>
              </li>
             
              <li class="article-tag-list-item">
                <a href="javascript:void(0)">工具</a>
              </li>
             
              <li class="article-tag-list-item">
                <a href="javascript:void(0)">chrome</a>
              </li>
             
              <li class="article-tag-list-item">
                <a href="javascript:void(0)">生活</a>
              </li>
             
              <li class="article-tag-list-item">
                <a href="javascript:void(0)">安全</a>
              </li>
             
              <li class="article-tag-list-item">
                <a href="javascript:void(0)">黑科技</a>
              </li>
             
              <li class="article-tag-list-item">
                <a href="javascript:void(0)">octopress</a>
              </li>
             
              <li class="article-tag-list-item">
                <a href="javascript:void(0)">浏览器</a>
              </li>
             
              <li class="article-tag-list-item">
                <a href="javascript:void(0)">主题</a>
              </li>
             
              <li class="article-tag-list-item">
                <a href="javascript:void(0)">hexo</a>
              </li>
             
              <li class="article-tag-list-item">
                <a href="javascript:void(0)">经验</a>
              </li>
             
              <li class="article-tag-list-item">
                <a href="javascript:void(0)">产品</a>
              </li>
             
              <li class="article-tag-list-item">
                <a href="javascript:void(0)">前端</a>
              </li>
             
              <li class="article-tag-list-item">
                <a href="javascript:void(0)">github</a>
              </li>
             
              <li class="article-tag-list-item">
                <a href="javascript:void(0)">药别停</a>
              </li>
             
              <li class="article-tag-list-item">
                <a href="javascript:void(0)">模式</a>
              </li>
             
              <li class="article-tag-list-item">
                <a href="javascript:void(0)">性能</a>
              </li>
            
            <div class="clearfix"></div>
          </ul>
        </div>
        <ul class="search-ul">
          <p q-show="jsonFail" style="padding: 20px; font-size: 12px;">
            缺失模块。<br/>1、在博客根目录（注意不是yilia根目录）执行以下命令：<br/> npm i hexo-generator-json-content --save<br/><br/>
            2、在根目录_config.yml里添加配置：
<pre style="font-size: 12px;" q-show="jsonFail">
  jsonContent:
    meta: false
    pages: false
    posts:
      title: true
      date: true
      path: true
      text: true
      raw: false
      content: false
      slug: false
      updated: false
      comments: false
      link: false
      permalink: false
      excerpt: false
      categories: false
      tags: true
</pre>
          </p>
          <li class="search-li" q-repeat="items" q-show="isShow">
            <a q-attr="href:path|urlformat" class="search-title"><i class="icon-quo-left icon"></i><span q-text="title"></span></a>
            <p class="search-time">
              <i class="icon-calendar icon"></i>
              <span q-text="date|dateformat"></span>
            </p>
            <p class="search-tag">
              <i class="icon-price-tags icon"></i>
              <span q-repeat="tags" q-on="click:choseTag(e, name)" q-text="name|tagformat"></span>
            </p>
          </li>
        </ul>
    	</section>
    

    

    
    	<section class="tools-section tools-section-me" q-show="aboutme">
  	  	
  	  		<div class="aboutme-wrap" id="js-aboutme">Litten，&lt;br&gt;毕业于华科，就职于鹅厂&lt;br&gt;&lt;br&gt;热爱大海与冷笑话，&lt;br/&gt;目前是一枚前端&lt;br/&gt;&lt;br/&gt;胆小认生，不易相处，&lt;br&gt;年轻无为，卖马为生。</div>
  	  	
    	</section>
    
  </div>
  
</div>
    <!-- Root element of PhotoSwipe. Must have class pswp. -->
<div class="pswp" tabindex="-1" role="dialog" aria-hidden="true">

    <!-- Background of PhotoSwipe. 
         It's a separate element as animating opacity is faster than rgba(). -->
    <div class="pswp__bg"></div>

    <!-- Slides wrapper with overflow:hidden. -->
    <div class="pswp__scroll-wrap">

        <!-- Container that holds slides. 
            PhotoSwipe keeps only 3 of them in the DOM to save memory.
            Don't modify these 3 pswp__item elements, data is added later on. -->
        <div class="pswp__container">
            <div class="pswp__item"></div>
            <div class="pswp__item"></div>
            <div class="pswp__item"></div>
        </div>

        <!-- Default (PhotoSwipeUI_Default) interface on top of sliding area. Can be changed. -->
        <div class="pswp__ui pswp__ui--hidden">

            <div class="pswp__top-bar">

                <!--  Controls are self-explanatory. Order can be changed. -->

                <div class="pswp__counter"></div>

                <button class="pswp__button pswp__button--close" title="Close (Esc)"></button>

                <button class="pswp__button pswp__button--share" style="display:none" title="Share"></button>

                <button class="pswp__button pswp__button--fs" title="Toggle fullscreen"></button>

                <button class="pswp__button pswp__button--zoom" title="Zoom in/out"></button>

                <!-- Preloader demo http://codepen.io/dimsemenov/pen/yyBWoR -->
                <!-- element will get class pswp__preloader--active when preloader is running -->
                <div class="pswp__preloader">
                    <div class="pswp__preloader__icn">
                      <div class="pswp__preloader__cut">
                        <div class="pswp__preloader__donut"></div>
                      </div>
                    </div>
                </div>
            </div>

            <div class="pswp__share-modal pswp__share-modal--hidden pswp__single-tap">
                <div class="pswp__share-tooltip"></div> 
            </div>

            <button class="pswp__button pswp__button--arrow--left" title="Previous (arrow left)">
            </button>

            <button class="pswp__button pswp__button--arrow--right" title="Next (arrow right)">
            </button>

            <div class="pswp__caption">
                <div class="pswp__caption__center"></div>
            </div>

        </div>

    </div>

</div>
  </div>
</body>
</html>